package com.chenfy.everysound

import android.media.MediaPlayer
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.chenfy.everysound.base.App
import com.chenfy.everysound.entity.SoundItem
import java.io.File

object SoundManager {
    val mediaPlayer by lazy {
        initMediaPlayer()
    }

    val playingItem = MutableLiveData<String>("")

    private fun initMediaPlayer(): MediaPlayer =
        MediaPlayer().apply {
            setOnPreparedListener {
                // 准备完成后就播放
                it.start()
            }
            setOnErrorListener { mp, what, extra ->
                true
            }
            setOnCompletionListener {
                playingItem.value = ""
            }
        }

    fun play(item: SoundItem) {
        mediaPlayer.reset()
        playingItem.value = ""
        val soundList = item.sound
        val context = App.context
        val fileDir = context.filesDir
        val soundFile = File(fileDir, soundList.random())
        Log.d("Chen","id:${item.id}")

        playingItem.value = item.id
        mediaPlayer.setDataSource(soundFile.absolutePath)
        mediaPlayer.prepareAsync()
    }
}